# -*- coding=utf-8 -*-
"""
baseline for Anti-UAV
https://anti-uav.github.io/
"""
from __future__ import absolute_import
import os
import glob
import json
import cv2
import numpy as np
from tqdm import tqdm
import sys
sys.path.insert(0, '/media/hp208/4t/zhaoxingjie/project_graduation/caffe/python')
import time
import matplotlib.pyplot as plt
import caffe

from google.protobuf import text_format
from caffe.proto import caffe_pb2


caffe.set_device(0)
caffe.set_mode_gpu()

# load PASCAL VOC labels
labelmap_file = './output/uav/labelmap_voc.prototxt'
file = open(labelmap_file, 'r')
labelmap = caffe_pb2.LabelMap()
text_format.Merge(str(file.read()), labelmap)

retest = True

model_def = './output/uav/deploy.prototxt'
model_weights = './output/uav/pelee_SSD_304x304_iter_60000.caffemodel'

# build the model from a config file and a checkpoint file
if retest:
    net = caffe.Net(model_def,      # defines the structure of the model
            model_weights,  # contains the trained weights
            caffe.TEST)     # use test mode (e.g., don't perform dropout)
    # input preprocessing: 'data' is the name of the input blob == net.inputs[0]
    transformer = caffe.io.Transformer({'data': net.blobs['data'].data.shape})
    transformer.set_transpose('data', (2, 0, 1))
    transformer.set_input_scale('data', 0.017)
    transformer.set_mean('data', np.array([103.94, 116.78, 123.68]))  # mean pixel
    transformer.set_raw_scale('data', 255)  # the reference model operates on images in [0,255] range instead of [0,1]
    transformer.set_channel_swap('data', (2, 1, 0))  # the reference model has channels in BGR order instead of RGB

else:
    net = None

colors=[]
for r in [0.2,0.4,0.8,0.6,1.0]:
    for g in [0.3,0.7]:
        for b in [0.4,0.8]:
            colors.append([r,g,b,1.0])

test_video_names = ['20190925_152412_1_7', '20190925_133630_1_2',
                    '20190925_133630_1_8', '20190926_143632_1_7',
                    '20190926_195921_1_9', '20190925_183946_1_8',
                    '20190925_101846_1_8', '20190925_200320_1_3',
                    '20190926_130341_1_1', '20190926_103046_1_1',
                    '20190925_140917_1_7', '20190926_144550_1_9',
                    '20190925_143900_1_4', '20190925_140917_1_4',
                    '20190926_183941_1_9', '20190926_144550_1_8',
                    '20190926_193515_1_3', '20190925_141417_1_8',
                    '20190925_200320_1_5', '20190926_133516_1_7']



def get_labelname(labelmap, labels):
    num_labels = len(labelmap.item)
    labelnames = []
    if type(labels) is not list:
        labels = [labels]
    for label in labels:
        found = False
        for i in xrange(0, num_labels):
            if label == labelmap.item[i].label:
                found = True
                labelnames.append(labelmap.item[i].display_name)
                break
        assert found == True
    return labelnames


def do_detect(image,colors):
    transformed_image = transformer.preprocess('data', image)
    net.blobs['data'].data[...] = transformed_image

    # Forward pass.
    detections = net.forward()['detection_out']
    detections = detections.squeeze()
    try:
        idx = np.argmax(detections[:, 2])
    except:
        return 0
    # Parse the outputs.

    det_conf = detections[idx,2]
    det_xmin = int(round(detections[idx,3] * image.shape[1]))
    det_ymin = int(round(detections[idx,4] * image.shape[0]))
    det_xmax = int(round(detections[idx,5] * image.shape[1]))
    det_ymax = int(round(detections[idx,6] * image.shape[0]))


    return [det_xmin, det_ymin, det_xmax - det_xmin, det_ymax - det_ymin]

def show_and_save_bar(vid_names, scores, save_dir, method):
    n_groups = len(vid_names)
    fig, ax = plt.subplots()
    index = np.arange(n_groups)
    bar_width = 1

    opacity = 0.4
    rects1 = plt.bar(index, scores, bar_width, alpha=opacity, color='y', label='Fixed Measure')
    plt.xlabel('VIDS')
    plt.ylabel('Fixed Measure')
    plt.title(method[:-3])
    # plt.xticks(index + bar_width, vid_names)
    # plt.xticks(rotation=90)
    # plt.ylim(0, 40)
    plt.legend()

    plt.tight_layout()
    plt.savefig(os.path.join(save_dir, 'result.png'), bbox_inches="tight", pad_inches=0.0)
    plt.show()

def save2csv(vid_names, scores, save_dir, method):
    import csv
    csv_path = os.path.join(save_dir, 'result_{}.csv'.format(method))
    with open(csv_path, 'w') as f:
        writer = csv.writer(f)
        # 将列表的每条数据依次写入csv文件， 并以逗号分隔
        # 传入的数据为列表中嵌套列表或元组，每一个列表或元组为每一行的数据
        writer.writerow(['vidname', 'score'])
        for vid_name, score in zip(vid_names, scores):
            writer.writerow([vid_name, score])
    print('save .csv file to {}.'.format(csv_path))

def iou(bbox1, bbox2):
    """
    Calculates the intersection-over-union of two bounding boxes.
    Args:
        bbox1 (numpy.array, list of floats): bounding box in format x,y,w,h.
        bbox2 (numpy.array, list of floats): bounding box in format x,y,w,h.
    Returns:
        int: intersection-over-onion of bbox1, bbox2
    """
    bbox1 = [float(x) for x in bbox1]
    bbox2 = [float(x) for x in bbox2]

    (x0_1, y0_1, w1_1, h1_1) = bbox1
    (x0_2, y0_2, w1_2, h1_2) = bbox2
    x1_1 = x0_1 + w1_1
    x1_2 = x0_2 + w1_2
    y1_1 = y0_1 + h1_1
    y1_2 = y0_2 + h1_2
    # get the overlap rectangle
    overlap_x0 = max(x0_1, x0_2)
    overlap_y0 = max(y0_1, y0_2)
    overlap_x1 = min(x1_1, x1_2)
    overlap_y1 = min(y1_1, y1_2)

    # check if there is an overlap
    if overlap_x1 - overlap_x0 <= 0 or overlap_y1 - overlap_y0 <= 0:
        return 0

    # if yes, calculate the ratio of the overlap to each ROI size and the unified size
    size_1 = (x1_1 - x0_1) * (y1_1 - y0_1)
    size_2 = (x1_2 - x0_2) * (y1_2 - y0_2)
    size_intersection = (overlap_x1 - overlap_x0) * (overlap_y1 - overlap_y0)
    size_union = size_1 + size_2 - size_intersection

    return size_intersection / size_union


def not_exist(pred):
    return len(pred) == 1 and pred == 0


def eval(out_res, label_res):
    measure_per_frame = []
    for _pred, _gt, _exist in zip(out_res, label_res['gt_rect'], label_res['exist']):
        measure_per_frame.append(not_exist(_pred) if not _exist else iou(_pred, _gt))
    return np.mean(measure_per_frame)


def main(mode='IR', visulization=False):
    assert mode in ['IR', 'RGB'], 'Only Support IR or RGB to evalute'


    work_dir = './evalroot'
    config_dir = 'ssdpelee'


    output_dir = os.path.join('antiuav_results', work_dir.split('/')[-1])


    # setup experiments
    # video_paths = glob.glob(os.path.join('dataset', 'test-dev', '*'))
    video_root = '/media/hp208/4t/zhaoxingjie/project_graduation/data/test-dev'
    video_paths = glob.glob('/media/hp208/4t/zhaoxingjie/project_graduation/data/test-dev/*')
    video_num = len(video_paths)

    if not os.path.exists(output_dir):
        os.makedirs(output_dir)
    overall_performance = []

    # run tracking experiments and report performance
    video_names = []
    total_time = 0
    img_count = 0
    # for video_id, video_path in enumerate(tqdm(video_paths), start=1):
    for video_id, video_name in enumerate(test_video_names):
        video_path = os.path.join(video_root, video_name)
        # video_name = os.path.basename(video_path)
        video_names.append(video_name)
        video_file = os.path.join(video_path, '%s.mp4'%mode)
        res_file = os.path.join(video_path, '%s_label.json'%mode)
        with open(res_file, 'r') as f:
            label_res = json.load(f)
        if retest:
            init_rect = label_res['gt_rect'][0]
            capture = cv2.VideoCapture(video_file)

            frame_id = 0
            out_res = []
            while True:
                ret, frame = capture.read()
                if not ret:
                    capture.release()
                    break
                # frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
                if frame_id == 0:
                    out = init_rect
                    aa = out
                    out_res.append(init_rect)
                else:
                    cv2.imwrite('./temp.jpg', frame)
                    image = caffe.io.load_imageimage = caffe.io.load_image('./temp.jpg')
                    start_time = time.time()
                    out = do_detect(image, colors)
                    end_time = time.time()
                    total_time += (end_time - start_time)
                    img_count += 1
                    if out != 0:
                        out_res.append(out)
                        # print out
                    else:
                        out_res.append([0, 0, 0, 0])
                    # print(frame_id)
                if visulization:
                    _gt = label_res['gt_rect'][frame_id]
                    _exist = label_res['exist'][frame_id]
                    if _exist:
                        cv2.rectangle(frame, (int(_gt[0]), int(_gt[1])), (int(_gt[0] + _gt[2]), int(_gt[1] + _gt[3])),
                                      (0, 255, 0))
                    cv2.putText(frame, 'exist' if _exist else 'not exist',
                                (frame.shape[1] // 2 - 20, 30), 1, 2, (0, 255, 0) if _exist else (0, 0, 255), 2)

                    cv2.rectangle(frame, (int(out[0]), int(out[1])), (int(out[0] + out[2]), int(out[1] + out[3])),
                                  (0, 255, 255))
                    cv2.imshow(video_name, frame)
                    cv2.waitKey(1)
                frame_id += 1
                print video_name, "---->", frame_id, img_count
            if visulization:
                cv2.destroyAllWindows()
            # save result
            output_file = os.path.join(output_dir, '%s_%s.txt' % (video_name, mode))
            with open(output_file, 'w') as f:
                json.dump({'res': out_res}, f)
        else:
            output_file = os.path.join(output_dir, '%s_%s.txt' % (video_name, mode))
            with open(output_file, 'r') as f:
                out_res = json.load(f)['res']

        mixed_measure = eval(out_res, label_res)
        overall_performance.append(mixed_measure)
        print('[%03d/%03d] %20s %5s Fixed Measure: %.03f, current_mean is %.3f' % (video_id, video_num, video_name, mode, mixed_measure, np.mean(overall_performance)))
    if retest:
        print "Total time ===>  {} ms, {}ms/img, fps = {}".format(total_time * 1000, total_time * 1000 / img_count, img_count / 1000000 / total_time)
    save2csv(video_names, overall_performance, work_dir, os.path.basename(work_dir))
    show_and_save_bar(video_names, overall_performance, work_dir, os.path.basename(work_dir))
    print('[Overall] %5s Mixed Measure: %.03f\n' % (mode, np.mean(overall_performance)))


if __name__ == '__main__':
    main(mode='IR', visulization=True)
